package com.pagepub.expo.dao;


import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.stereotype.Repository;

import com.pagepub.expo.entity.AppSeq;

@Repository("appSeqDao")
public class AppSeqDao {

	@Autowired
	@Qualifier("jdbcTemplate")
	private JdbcTemplate template;

	private static String QUERY_ALL = "SELECT id,seqName,seqValue FROM App_Seq ";
	
	private static String UPDATE_SQL = "UPDATE App_Seq SET seqValue=:seqValue WHERE seqName=:seqName";

	private final ParameterizedRowMapper<AppSeq> appMapper = new ParameterizedRowMapper<AppSeq>() {
		public AppSeq mapRow(ResultSet rs, int rowNum) throws SQLException {
			AppSeq as = new AppSeq();
			as.setId(rs.getLong("id"));
			as.setSeqName(rs.getString("seqName"));
			as.setSeqValue(rs.getInt("seqValue"));
			return as;
		}
	};
	
	
	public int getDefault() {
		int seq;
		String sequence="app_seq";
		AppSeq appSeq=this.findById(sequence);
		seq=appSeq.getSeqValue()+1;
		this.update(appSeq);
		return seq;

	}
	
	public int getSequence(String sequence) {
		int seq;
		AppSeq appSeq=this.findById(sequence);
		seq=appSeq.getSeqValue()+1;
		appSeq.setSeqValue(seq);
		this.update(appSeq);
		return seq;
	}
	
	public AppSeq findById(String sequence) {
		List<AppSeq> appSeqs = template.query(QUERY_ALL + " WHERE seqName=?",
				new Object[] { sequence }, appMapper);
		if (appSeqs.size() == 0) {
			return null;
		} else
			return appSeqs.get(0);
	}
	
	public void update(AppSeq appSeq) {
		SqlParameterSource ps = new BeanPropertySqlParameterSource(appSeq);
		NamedParameterJdbcTemplate npTemplate = new NamedParameterJdbcTemplate(
				template.getDataSource());
		npTemplate.update(UPDATE_SQL, ps);
	}

	
}

